package com.glorysoft.knowlespda.utils

import android.text.TextUtils
import androidx.fragment.app.FragmentManager
import com.glorysoft.knowlespda.R
import com.glorysoft.knowlespda.base.MyApp
import com.glorysoft.knowlespda.entity.net.BaseResponseBean
import com.glorysoft.knowlespda.utils.FreeApi_DialogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.entity.ParameterizedTypeImpl
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.AbstractParser
import rxhttp.wrapper.utils.convert
import java.io.IOException
import java.lang.reflect.Type

/**
 * 输入T,输出T,并对code统一判断
 *
 * 如果使用协程发送请求，wrappers属性可不设置，设置了也无效
 */
@Parser(name = "Response")
open class ResponseParser<T> : AbstractParser<T> {
    /**
     * 此构造方法适用于任意Class对象，但更多用于带泛型的Class对象，如：List<Student>
     *
     * 用法:
     * Java: .asParser(new ResponseParser<List<Student>>(){})
     * Kotlin: .asParser(object : ResponseParser<List<Student>>() {})
     *
     * 注：此构造方法一定要用protected关键字修饰，否则调用此构造方法将拿不到泛型类型
     */
    protected constructor() : super()

    /**
     * 此构造方法仅适用于不带泛型的Class对象，如: Student.class
     *
     * 用法
     * Java: .asParser(new ResponseParser<>(Student.class))   或者  .asResponse(Student.class)
     * Kotlin: .asParser(ResponseParser(Student::class.java)) 或者  .asResponse<Student>()
     */
    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T {
        val type: Type = ParameterizedTypeImpl[BaseResponseBean::class.java, mType] //获取泛型类型
        val data: BaseResponseBean<T> = response.convert(type)
        var t = data.data //获取data字段

        if (data.code != 0 ) {

            if (!TextUtils.isEmpty(data.message)) {
                throw ParseException(data.code.toString(), data.message, response)
            }else{
                throw ParseException(data.code.toString(), data.code.toString(), response)
            }
        }else{
            if (data.message.isNotEmpty()){
                Tip.runOnUiThread {
//                    val duration = Toast.LENGTH_SHORT
//                    FreeApi_ToastUtils.showFreeToast(
//                        data.message,
//                        MyApp.getInstance(),
//                        true,
//                        duration
//                    )
                    showFailDialog(data.message,MyApp.getSupportFragmentManager())
                }
            }
        }
        return t.body
    }
    fun showFailDialog(message: String, fragmentManager: FragmentManager) {
        val tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, MyApp.app.getString(R.string.confirm), message,MyApp.app.getString(R.string.tips)) {}
        tipDialog.show(fragmentManager, "DIALOG")
    }
}